import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:mall/core/models/point_transfer.dart';
import 'package:mall/core/services/new_api.dart';
import 'package:mall/screens/point/point_transfer_history_screen.dart';
import 'package:provider/provider.dart';
import 'package:intl/intl.dart';

class PointTransferQueryScreen extends StatefulWidget {
  static const routeName = '/PointTransferQueryScreen';

  @override
  _PointTransferQueryScreenState createState() => _PointTransferQueryScreenState();
}

class _PointTransferQueryScreenState extends State<PointTransferQueryScreen> {
  final DateFormat _dateFormat = DateFormat("yyyy-MM-dd");

  String _error;
  PointTransferQueryParam _param;

  AccountTypeItem _accountTypeItem;
  String _outUsername;
  String _inUsername;
  DateTime _startTime;
  DateTime _endTime;

  TextEditingController _outUsernameController;
  TextEditingController _inUsernameController;

  @override
  void initState() {
    super.initState();
    _outUsernameController = TextEditingController();
    _inUsernameController = TextEditingController();
    _fetchPointTransferQueryParam();
  }

  @override
  void dispose() {
    _outUsernameController.dispose();
    _inUsernameController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('转赠查询'),
      ),
      body: _error == null && _param == null
          ? Center(
              child: CircularProgressIndicator(),
            )
          : _param == null
              ? Center(
                  child: Text(_error),
                )
              : _buildBody(),
    );
  }

  Widget _buildBody() {
    return Padding(
      padding: EdgeInsets.all(8.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text("请选择积分类型："),
          Container(
            width: double.infinity,
            child: OutlinedButton(
              onPressed: _showAccountType,
              child: Text(_accountTypeItem == null ? "请选择" : _accountTypeItem.name),
            ),
          ),
          if (_param.outUsernames != null) ...[
            SizedBox(
              height: 8.w,
            ),
            Text("请选择赠出账号："),
            Container(
              width: double.infinity,
              child: OutlinedButton(
                onPressed: _showOutUsername,
                child: Text(_outUsername == null ? "请选择" : _outUsername),
              ),
            ),
          ],
          if (_param.outUsernames == null) ...[
            SizedBox(
              height: 8.w,
            ),
            Text("请输入赠出账号："),
            TextField(
              controller: _outUsernameController,
              decoration: InputDecoration(
                hintText: "输入",
              ),
              onChanged: (value) {
                _outUsername = value;
              },
            ),
          ],
          if (_param.inUsernames != null) ...[
            SizedBox(
              height: 8.w,
            ),
            Text("请选择受赠账号："),
            Container(
              width: double.infinity,
              child: OutlinedButton(
                onPressed: _showInUsername,
                child: Text(_inUsername == null ? "请选择" : _inUsername),
              ),
            ),
          ],
          if (_param.inUsernames == null) ...[
            SizedBox(
              height: 8.w,
            ),
            Text("请输入受赠账号："),
            TextField(
              controller: _inUsernameController,
              decoration: InputDecoration(
                hintText: "输入",
              ),
              onChanged: (value) {
                _inUsername = value;
              },
            ),
          ],
          SizedBox(
            height: 8.w,
          ),
          Text("请选择起始日期："),
          Container(
            width: double.infinity,
            child: OutlinedButton(
              onPressed: () {
                DatePicker.showDatePicker(
                  context,
                  maxTime: _endTime,
                  onConfirm: (value) {
                    setState(() {
                      _startTime = value;
                    });
                  },
                  locale: LocaleType.zh,
                );
              },
              child: Text(_startTime == null ? "请选择" : _dateFormat.format(_startTime)),
            ),
          ),
          SizedBox(
            height: 8.w,
          ),
          Text("请选择截止日期："),
          Container(
            width: double.infinity,
            child: OutlinedButton(
              onPressed: () {
                DatePicker.showDatePicker(
                  context,
                  minTime: _startTime,
                  onConfirm: (value) {
                    setState(() {
                      _endTime = value;
                    });
                  },
                  locale: LocaleType.zh,
                );
              },
              child: Text(_endTime == null ? "请选择" : _dateFormat.format(_endTime)),
            ),
          ),
          SizedBox(
            height: 8.w,
          ),
          Row(
            children: [
              Spacer(),
              OutlinedButton(
                onPressed: _clearParam,
                child: Text("清空条件"),
              ),
              Spacer(),
              ElevatedButton(
                onPressed: _query,
                child: Text("查询"),
              ),
              Spacer(),
            ],
          )
        ],
      ),
    );
  }

  /// 获取查询参数
  void _fetchPointTransferQueryParam() async {
    final api = context.read<NewApi>();
    try {
      final pointTransferQueryParam = await api.pointTransferQueryParam();
      if (!mounted) {
        return;
      }
      setState(() {
        _param = pointTransferQueryParam;
      });
    } on DioError catch (e) {
      if (!mounted) {
        return;
      }
      setState(() {
        _error = e.message;
      });
    }
  }

  /// 显示账号
  void _showAccountType() async {
    final accountTypeItem = await showModalBottomSheet(
      context: context,
      builder: (context) {
        return ListView.builder(
          itemBuilder: (context, index) {
            final data = _param.accountTypes[index];
            return ListTile(
              title: Text("${data.name}"),
              onTap: () => Navigator.of(context).pop(data),
            );
          },
          itemCount: _param.accountTypes.length,
        );
      },
    );
    if (accountTypeItem != null) {
      setState(() {
        _accountTypeItem = accountTypeItem;
      });
    }
  }

  /// 选择赠出账号
  void _showOutUsername() async {
    final outUsername = await showModalBottomSheet(
      context: context,
      builder: (context) {
        return ListView.builder(
          itemBuilder: (context, index) {
            final data = _param.outUsernames[index];
            return ListTile(
              title: Text("$data"),
              onTap: () => Navigator.of(context).pop(data),
            );
          },
        );
      },
    );
    if (outUsername != null) {
      setState(() {
        _outUsername = outUsername;
      });
    }
  }

  /// 选择受赠账号
  void _showInUsername() async {
    final inUsername = await showModalBottomSheet(
      context: context,
      builder: (context) {
        return ListView.builder(
          itemBuilder: (context, index) {
            final data = _param.inUsernames[index];
            return ListTile(
              title: Text("$data"),
              onTap: () => Navigator.of(context).pop(data),
            );
          },
        );
      },
    );
    if (inUsername != null) {
      setState(() {
        _inUsername = inUsername;
      });
    }
  }

  /// 清空条件
  void _clearParam() {
    setState(() {
      _accountTypeItem = null;
      _outUsername = null;
      _inUsername = null;
      _startTime = null;
      _endTime = null;
    });
    _inUsernameController.clear();
    _outUsernameController.clear();
  }

  /// 查询
  void _query() {
    final req = PointTransferQueryReq(
      accountType: _accountTypeItem?.accountType,
      inUsername: _inUsername,
      outUsername: _outUsername,
      startTime: _startTime == null ? null : _dateFormat.format(_startTime),
      endTime: _endTime == null ? null : _dateFormat.format(_endTime),
      pageIndex: 0,
      pageSize: 10,
    );
    Navigator.of(context).pushReplacementNamed(
      PointTransferHistoryScreen.routeName,
      arguments: req,
    );
  }
}
